package com.itcast.controller;

import com.itcast.pojo.User;
import com.itcast.service.UserService;
import com.itcast.service.UserServiceImpl;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@WebServlet("/RegistServlet")
@MultipartConfig
public class RegistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 通过表单file控件(<input type="file" name="head">)的名字直接获取Part对象
        Part part=request.getPart("head");
        String disposition = part.getHeader("Content-Disposition");
        //lastIndexOf返回指定子字符串在此字符串中最右边出现处的索引，如果此字符串中没有这样的字符，则返回 -1。
        String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
        //UUID在一定的范围内（从特定的名字空间到全球）唯一的机器生成的标识符。
        String filename = UUID.randomUUID()+suffix;
        InputStream is = part.getInputStream();
        String storePath=request.getSession().getServletContext().getRealPath("/upload");
        //实例化输出流，然后调用流的读写方法读取或写入数据，最后关闭流。
        FileOutputStream fos = new FileOutputStream(storePath+"/"+filename);
        
        byte[] bty = new byte[1024];
        int length =0;
        while((length=is.read(bty))!=-1){
            fos.write(bty,0,length);
        }
        fos.close();
        is.close();
        System.out.println("文件上传成功!");
        String Id=request.getParameter("Id");
        String uname=request.getParameter("uname");
        String upwd=request.getParameter("upwd");
        User user=new User();
        user.setUserId(Id);
        user.setUserName(uname);
        user.setUserImage(filename);
        user.setUserPassword(upwd);
        UserService userService=new UserServiceImpl();
        userService.InsertUser(user);
        request.getRequestDispatcher("/page/login.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
